package de.stalinski.db;

import de.stalinski.logging.FrbrLogger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class LoginDatabaseConnector {

    private static LoginDatabaseConnector LoginDatabaseConnector;
    private FrbrLogger logger = FrbrLogger.instance();
    private static String sUsr = "root";
    private static String sPwd = "admin";
    private static String sDB = "frbrUsers";
    private static String sTable = "customers";
    private static Connection connection;
    private static String sHost = "localhost";
    private static String sConn = "jdbc:mysql://" + sHost + ":3306/" + sDB;

    public static LoginDatabaseConnector instance() {
        System.out.println(sConn);
        if (LoginDatabaseConnector == null) {
            LoginDatabaseConnector = new LoginDatabaseConnector();
        }
        return LoginDatabaseConnector;
    }

    private LoginDatabaseConnector() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
        try {
            connection = DriverManager.getConnection(sConn, sUsr, sPwd);
            System.out.println(connection != null);
        } catch (SQLException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
    }

    public boolean doQuery(String user, String pw) {
        try {
            Statement st = null;
            ResultSet rs = null;
            st = connection.createStatement();
            rs = st.executeQuery("select * from " + sTable);
            // Get meta data:
            ResultSetMetaData rsmd = rs.getMetaData();
            int i;
            int n = rsmd.getColumnCount();

            while (rs.next()) {
                    System.out.println(rs.getString("Username"));
                if (rs.getString("Username").equals(user)) {

                    if (rs.getString("pass").equals(pw)) {

                        return true;
                    } else {

                        return false;
                    }
                }

            }
        } catch (SQLException ex) {
            logger.log(logger.LOG_ERR, ex.toString());
        }
        return false;
    }
}
